//
//  BaseTableViewController.m
//  Cypress
//
//  Created by 张如进 on 13-5-16.
//  Copyright (c) 2013年 Raiyi. All rights reserved.
//

#import "BaseTableViewController.h"
#import "HttpBaseAction.h"

@interface BaseTableViewController () {
    BOOL _isLoadingMore;
    BOOL _hasMore;
    BOOL _refresh;
    UIView *_refreshView;
    UIView *_loadingMoreView;
    UIView *_noResultView;
    BOOL _enabledLoadMore;
    SEL sel;
    id obj;
}
@property (nonatomic,strong) NSString *className;

@property (nonatomic,strong) UIView *loadingMoreView;

@end

@implementation BaseTableViewController
//@synthesize tableView = _tableView;
@synthesize loadingMoreView = _loadingMoreView;
@synthesize enabledLoadMore = _enabledLoadMore;
@synthesize hasMore = _hasMore;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super init];
    if (self) {
        
        self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectZero style:style];
        _tableView.backgroundView = nil;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
//        _tableView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleHeight;
        _tableView.scrollsToTop = YES;
        // Custom initialization
    }
    return self;
}

- (id)init{
    return [self initWithStyle:UITableViewStylePlain];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.view.autoresizesSubviews = YES;
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    [self.view addSubview:self.tableView];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(void)loadHeader{
    self.offset = 1;
    [self loadList];
}

-(void)loadFooter{
    self.offset++;
    [self loadList];
    
}

-(void)loadList{
    HTTPResultBlock block = ^(id result, NSError *error) {
        if (!error) {
            NSArray *array = result;
            if (self.offset == 1) {
                self.resultArray = result;
            }else{
                [self.resultArray addObjectsFromArray:array];
            }
            if (self.resultArray.count == 0) {
                [self showNoResult];
            }
            [self.tableView reloadData];
            if (array.count<10) {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
            
        }else{
            [self.tableView.mj_header endRefreshing];
            [self showMessage:error.domain autoDissmissAfterDelay:0];
        }
        
    };
    Class c = NSClassFromString(self.className);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[Utils objectToDictionary:obj]];
    [dic setObject:[NSString stringWithFormat:@"%d",self.offset] forKey:@"page"];
    [c performSelector:sel withObject:dic withObject:block];
    
}

-(void)setClass:(NSString*)className action:(SEL)action{
    self.className = className;
    sel = action;
}

-(void)setClass:(NSString*)className action:(SEL)action object:(id)object{
    self.className = className;
    sel = action;
    obj = object;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // Configure the cell...
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}


#pragma mark - UIScrollView Delegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    if (scrollView==self.tableView&&_refresh == YES) {
        if (scrollView.contentOffset.y < -44){
            [UIView animateWithDuration:0.18f animations:^{
                [self showLoadingRefreshView];
            }];
            [self refreshData:^(BOOL refresh, BOOL loading) {
                if (loading==NO) {
                    [UIView animateWithDuration:0.18f animations:^{
                        self.tableView.tableHeaderView = nil;
                    }];
                }
            }];
        }
    }
    
    
    if (_enabledLoadMore == YES && scrollView == self.tableView) {
        if (_isLoadingMore == NO && _hasMore == YES) {
            if (scrollView.contentOffset.y > scrollView.contentSize.height + 44 - scrollView.frame.size.height) {
                [self showLoadingMoreView];
                
                //Modify:沈海华 2013-07-29	注释本文件loadingMore方法调用
                [self loadMoreData:^(BOOL hasMore, BOOL loading) {
                    _hasMore = hasMore;
                    if (loading == NO) {
                        [self hiddenLoadingMoreView];
                    }
                    if (_hasMore == NO) {
                        [self showNoMoreResultView];
                    }
                }];
                //End
            }
        }else if(_isLoadingMore == NO && _hasMore == NO){
            [self showNoMoreResultView];
        }
    }
}

- (void)loadMoreData:(void (^)(BOOL hasMore, BOOL loading)) block{
    block(NO,NO);
}

- (void)refreshData:(void (^)(BOOL refresh,BOOL loading)) block{
    block(NO,NO);
}



-(void)showNoResultViewWithTitle:(NSString*)title{
    if (_noResultView == nil) {
        _noResultView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, SCREEN_WIDTH, 200)];
        _noResultView.backgroundColor = self.view.backgroundColor;
        [self.tableView addSubview:_noResultView];
        
        UILabel *label =[[UILabel alloc] initWithFrame:_noResultView.bounds];
        label.textAlignment=NSTextAlignmentCenter;
        label.textColor=[UIColor blackColor];
        label.backgroundColor=[UIColor clearColor];
        label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor darkGrayColor];
        if (title==nil) {
            label.text=@"没有搜索到相关数据";
        }else{
            label.text=title;
        }
        
        [_noResultView addSubview:label];
    }
    _noResultView.hidden = NO;
}

-(void)showNoResultView {
    [self showNoResultViewWithTitle:nil];
}

- (void)hiddenNoResultView{
    _noResultView.hidden = YES;
}
#pragma mark - Loading

- (void)showNoMoreResultView {
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, SCREEN_WIDTH, 44)];
    label.textAlignment=NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor darkGrayColor];
    label.backgroundColor = self.view.backgroundColor;
    label.text = @"没有更多数据了!";
    self.tableView.tableFooterView=label;
}

- (void)hiddenNoMoreResultView {
    self.tableView.tableFooterView = nil;
}

- (void) showLoadingRefreshView{
    if (_refreshView == nil) {
        UIView *loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityView.center = loadingView.center;
        [loadingView addSubview:activityView];
        [activityView startAnimating];
        _refreshView = loadingView;
    }
    self.tableView.tableHeaderView = _refreshView;
}

- (void)showLoadingMoreView {
    _isLoadingMore = YES;
    if (_loadingMoreView == nil) {
        UIView *loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityView.center = loadingView.center;
        [loadingView addSubview:activityView];
        [activityView startAnimating];
        self.loadingMoreView = loadingView;
    }
    self.tableView.tableFooterView = _loadingMoreView;
}

- (void)hiddenLoadingMoreView {
    [self dismissWaitingView];
    _isLoadingMore = NO;
    self.tableView.tableFooterView = nil;
}


#pragma mark -

- (NSInteger)numberOfEveryPage {
    return 10;
}

- (NSInteger)currentPage {
    return 0;
}

-(void)showNoResult{
    if (_noResultView == nil) {
        int height = self.tableView.frameHeight;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        UIImageView *noImageView = [UIImageView new];
        noImageView.image = [UIImage imageNamed:@"noresult"];
        [view addSubview:noImageView];
        noImageView.sd_layout.centerXIs(SCREEN_WIDTH/2).centerYIs(height/2-40).widthIs(90).heightIs(90);
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textColor = [UIColor grayColor];
        [view addSubview:titleLabel];
        titleLabel.sd_layout.centerXIs(SCREEN_WIDTH/2-5).centerYIs(height/2+20).widthIs(SCREEN_WIDTH).heightIs(20);
        titleLabel.text = @"目前没有数据";
        [self.tableView addSubview:view];
        _noResultView = view;
    }
    
}

-(void)showNoResultWithFrame:(CGRect)rect{
    if (_noResultView == nil) {
        int height = rect.size.height;
        UIView *view = [[UIView alloc] initWithFrame:rect];

        UIImageView *noImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-45, height/2-85, 90, 90)];
        noImageView.image = [UIImage imageNamed:@"noresult"];
        [view addSubview:noImageView];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, noImageView.frameBottom+10, SCREEN_WIDTH, 20)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textColor = [UIColor grayColor];
        [view addSubview:titleLabel];
        titleLabel.text = @"目前没有数据";
        [self.tableView addSubview:view];
        _noResultView = view;
    }
}

@end
